I want the function "amongst" or "within" in lodash or JS. The opposite already exists, it is called "includes". Example :
_(['a', 42]).includes(42)
I would like to write
_(42).amongst(['a', 42])
Any clues ?
Your amongst / within function is a version of _.includes() with the search value 1st and the collection 2nd, so you can create one easily by flipping _.includes():
const amongst = _.flip(_.includes)
console.log(amongst(42, ['a', 42]))
console.log(amongst('b', ['a', 42]))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
And you can use _.mixin() to add it to lodash:
const amongst = _.flip(_.includes)
_.mixin({ amongst });
console.log(_(42).amongst(['a', 42]))
console.log(_('b').amongst(['a', 42]))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
In vanillaJS you can create a function that does the same thing:
const amongst = (value, collection) => collection.includes(value)
console.log(amongst(42, ['a', 42]))
console.log(amongst('b', ['a', 42]))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>